import { createRouter, createWebHistory } from 'vue-router';
import beforeEach from './beforeEach';

const requireModules = require.context('./modules', true, /(.js$)/);
const routes = requireModules
  .keys()
  .map((filePath) => requireModules(filePath).default)
  .flat();

const router = createRouter({
  scrollBehavior(to, from, savedPosition) {
    return savedPosition || { x: 0, y: 0 };
  },
  history: createWebHistory('/app'),
  routes,
});

beforeEach.forEach((item) => {
  router.beforeEach(item).bind(router);
});

// 路由切换成功
// router.afterEach((route) => {
//   try {
//   } catch (error) {
//     throw new Error(error);
//   }
// });

// router.onError(vueRouterError);

const install = router.install;

router.install = function install2(app) {
  router.app = app;
  install.apply(this, [app]);
};
// 路由
export default router;
